import java.util.*;

/**
 * JSMsgProtocolServer - The server protocol for Jam Session
 * 
 * @author James Varvaro
 */
public class JSMsgProtocolServer {
    JSServerThread st;
    
    public JSMsgProtocolServer(JSServerThread ast) {
        this.st = ast;
    }
    
    public void process(String msg) {
        StringTokenizer tokens = new StringTokenizer(msg);
        // Retrieve message type {CONNECTION, NOTE, or CHANGE}
        if(tokens.countTokens() > 3) {
            String msgType = tokens.nextToken();
            String userid = tokens.nextToken();
            String username = tokens.nextToken();
            if(msgType.equals("NOTE")) {
                // Extract note info
                String noteid = tokens.nextToken();
                String instrumentType = tokens.nextToken();
                String pitch = tokens.nextToken();
                String noteStatus = tokens.nextToken();
                
                st.broadcastToAll(msg);
                
            }
            else if(msgType.equals("CHANGE")) {
            }
            else if(msgType.equals("CONNECTION")) {
                String connectionType = tokens.nextToken();
                String connectionStatus = tokens.nextToken();
                if(connectionType.equals("connect")) {
                    if(connectionStatus.equals("true")) {
                        // connect client
                        long id = st.registerUser(username);
                        String response = "CONNECTION " + id + " " + username + " notify " + "true";
                        st.broadcastToClient(response);
                    }
                    else if(connectionStatus.equals("false")) {
                        // disconnect client
                        this.st.disconnectUser();
                    }
                    else {
                        System.out.println("Not a valid connection status.");
                    }
                }
            }
            else {
                System.out.println("Invalid msg from server.");
            }
        }
        else {
            System.out.println("invalid message: not enough tokens: " + msg);
        }
    }
}
